<template>
  <div>
    <!-- SPU添加或修改组件 -->
    <el-form label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请输入品牌" v-model="spu.tmId">
          <el-option
            :value="trademark.id"
            v-for="trademark in spuTrademarkList"
            :key="trademark.id"
            :label="trademark.tmName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          placeholder="SPU描述"
          type="textarea"
          rows="4"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" :disabled="!UnSelectAttr">
        <el-select
          :placeholder="`还有${UnSelectAttr.length}未选择`"
          v-model="attrIdAndName"
        >
          <el-option
            v-for="item in UnSelectAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          :disabled="!attrIdAndName"
          @click="addAttrValue"
          >添加销售属性</el-button
        >
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" align="center" width="80">
          </el-table-column>
          <el-table-column prop="saleAttrName" width="width" label="属性名">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <!--展示已有属性值列表的属性-->
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- 添加属性值输入框-->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                @keyup.enter.native="handleInputConfirm(row)"
                ref="saveTagInput"
                size="small"
                v-model="row.inputValue"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <!-- 添加属性值按钮-->
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" width="width" label="操作">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="SaveSpuAttrList">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  props: {},
  components: {},
  data() {
    return {
      // 图片路径
      dialogImageUrl: "",
      // 对话框是否显示
      dialogVisible: false,
      spu: {
        category3Id: 0,
        description: "",
        spuImageList: [],
        spuName: "",
        spuSaleAttrList: [],
        tmId: "",
      },
      spuTrademarkList: [],
      spuImageList: [],
      spuSaleAttrList: [],
      // 收集未选择的销售属性
      attrIdAndName: "",
    };
  },
  computed: {
    // 过滤未选择得平台销售属性
    UnSelectAttr() {
      const result = this.spuSaleAttrList.filter((item1) => {
        return this.spu.spuSaleAttrList.every((item) => {
          return item1.name != item.saleAttrName;
        });
      });
      return result;
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    //   图片删除的回调
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.spuImageList = fileList;
    },
    // 图片放大显示的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功的回调
    handleSuccess(response, file, fileList) {
      // 收集数据
      console.log(file, fileList);
      this.spuImageList = fileList;
    },
    // 初始化SPU数据
    async InitSpuData(spu) {
      // 获取SPU信息
      const spuResult = await this.$API.spu.reqSPU(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      // 获取品牌信息
      const spuTrademark = await this.$API.spu.reqTradeMarkList();
      console.log(spuTrademark);
      if (spuTrademark.code == 200) {
        this.spuTrademarkList = spuTrademark.data;
      }
      // 获取图片信息
      const spuImageList = await this.$API.spu.reqSpuImageList(spu.id);
      console.log(spuImageList);
      if (spuImageList.code == 200) {
        this.spuImageList = spuImageList.data;
      }
      // 获取平台销售属性列表
      const spuSaleAttrList = await this.$API.spu.reqBaseSaleAttrList();
      console.log(spuSaleAttrList);
      if (spuSaleAttrList.code == 200) {
        this.spuSaleAttrList = spuSaleAttrList.data;
      }
    },
    // 添加销售属性功能
    addAttrValue() {
      // 获取选择的销售属性id和姓名
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndName.split(":");
      // 创建添加的销售属性列表
      const newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      //  添加销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
      // 清空数据
      this.attrIdAndName = "";
    },
    // 添加属性值功能
    showInput(row) {
      // 设置状态切换属性
      this.$set(row, "inputVisible", true);
      // 设置输入框的默认值
      this.$set(row, "inputValue", "");
    },
    // 添加属性输入框回调
    handleInputConfirm(row) {
      // 解构需要的的属性
      const { baseSaleAttrId, inputValue } = row;
      // 过滤空值和重复值的情况
      if (inputValue == "") {
        this.$message("属性值不能为空");
        return;
      }
      // 遍历数组寻找重复值
      const res = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === inputValue
      );
      // console.log(res);
      if (res) {
        this.$message("属性值不能重复");
        return;
      }
      // 整理数据后添加数据
      let newAttrList = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newAttrList);
      // 切换状态
      row.inputVisible = false;
    },
    // 保存功能
    async SaveSpuAttrList() {
      // 整理照片墙数据
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      const res = await this.$API.spu.reqAddOrUpdateAttrList(this.spu);
      // console.log(res);
      // 成功则跳转回SPU管理页面
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "保存成功",  
        });
      }
      // 切换场景值
      this.$emit("ChangeScene",{scene:0,flag:this.spu.id?"修改":"添加"});
      // 清除数据
      Object.assign(this._data,this.$options.data())
    },
    // 添加SPU属性初始化数据
    async addSpuData(category3Id) {
      // 收集三级分类ID
      // 获取品牌信息
      const spuTrademark = await this.$API.spu.reqTradeMarkList();
      console.log(spuTrademark);
      if (spuTrademark.code == 200) {
        this.spuTrademarkList = spuTrademark.data;
      }
      // 获取平台销售属性列表
      const spuSaleAttrList = await this.$API.spu.reqBaseSaleAttrList();
      console.log(spuSaleAttrList);
      if (spuSaleAttrList.code == 200) {
        this.spuSaleAttrList = spuSaleAttrList.data;
      }
    },
    // 取消功能回调
    cancel(){
      // 切换场景
      this.$emit('ChangeScene', {scene:0,flag:''});
      // 清除数据
      Object.assign(this._data,this.$options.data())
    }
  },
};
</script>

<style scoped lang="less"></style>
